import React, { useCallback, useEffect, useState } from "react";
import request from "../../utils/request";
import API from "../../utils/api";
import { ApplicationEntity } from "../../entity/Application";
import { Input, message } from "antd";
import { debounce } from "lodash";
import App from "./App";
import "./index.less";

const Applications: React.FC = () => {
    const [applications, setApplications] = useState<ApplicationEntity[]>([]);
    const [keyword, setKeyWord] = useState<string | undefined>();
    useEffect(() => {
        request<ApplicationEntity[]>(API.GET_APPLICATION_LIST).then(res => {
            if (res.success) {
                setApplications(res.data);
            } else {
                message.error(res.message);
            }
        });
    }, []);

    const func = debounce((value: string) => {
        setKeyWord(value);
    }, 500);

    const setSearch = useCallback((event: React.ChangeEvent<HTMLInputElement>) => {
        func(event.target.value);
    }, []);

    return (
        <div className='app-content'>
            <Input.Search autoFocus onChange={setSearch}/>
            <div className='app-list'>
                <div className='app-labels'>
                    <span>全部（{applications.length}）</span>
                </div>
                <div style={{flex: 1, overflowY: "auto", overflowX: "hidden"}}>
                    {applications.filter(a => {
                        if (!keyword && keyword !== "") {
                            return true;
                        }
                        return a.name.includes(keyword);
                    }).map(app => (
                        <App {...app} key={app.id}/>
                    ))}
                </div>
            </div>
        </div>
    );
};

export default Applications;
